package woa.binarysearch;

import java.util.*;

/**
 * 两个数组的交集 II
 * 给你两个整数数组 nums1 和 nums2 ，请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数，应与元素在两个数组中都出
 * 现的次数一致（如果出现次数不一致，则考虑取较小值）。可以不考虑输出结果的顺序。
 *
 * 输入：nums1 = [1,2,2,1], nums2 = [2,2]
 * 输出：[2,2]
 *
 * @author wangpeng
 * @date 2021/12/22
 */
public class Intersect2 {

    public static int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map1 = toMap(nums1);
        Map<Integer, Integer> map2 = toMap(nums2);
        int len1 = map1.size();
        int len2 = map2.size();
        Map<Integer, Integer> sMap = len1 > len2 ? map2 : map1;
        Map<Integer, Integer> lMap = len1 > len2 ? map1 : map2;
        List<Integer> list = new ArrayList<>();
        for (Integer key : sMap.keySet()){
            if (lMap.containsKey(key)) {
                int size = sMap.get(key) < lMap.get(key) ? sMap.get(key) : lMap.get(key);
                for (int i = 0; i < size; i++) {
                    list.add(key);
                }
            }
        }
        int[] rs = new int[list.size()];
        for (int i = 0; i < rs.length; i++) {
            rs[i] = list.get(i);
        }
        return rs;
    }

    public static Map<Integer, Integer> toMap(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }

        return map;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(intersect(new int[]{4,9,4,5,9}, new int[]{9,4,9,8,4})));
    }
}
